Python Sets Quick Reference

Table Of Contents

1. Construction


In [18]:
# create an empty set
empty_set = set()
empty_set


Out[18]:
set()

In [19]:
# create a set directly
languages = {'python', 'r', 'java'}
languages


Out[19]:
{'java', 'python', 'r'}

In [20]:
#create a set from a list
snakes = set(['cobra', 'viper', 'python'])
snakes


Out[20]:
{'cobra', 'python', 'viper'}

2. Accessing Data


In [21]:
len(languages)


Out[21]:
3

In [22]:
'python' in languages


Out[22]:
True

3. Modifying


In [23]:
# add a new element
languages.add('sql')
languages


Out[23]:
{'java', 'python', 'r', 'sql'}

In [24]:
# try to add an existing element (ignored, no error)
languages.add('r')
languages


Out[24]:
{'java', 'python', 'r', 'sql'}

In [25]:
# remove an element
languages.remove('java')
languages


Out[25]:
{'python', 'r', 'sql'}

In [26]:
# try to remove a non-existing element (this would throw an error)
# languages.remove('c')

In [27]:
# remove an element if present, but ignored otherwise
languages.discard('c')
languages


Out[27]:
{'python', 'r', 'sql'}

In [28]:
# remove and return an arbitrary element
languages.pop()


Out[28]:
'python'

In [29]:
# remove all elements
languages.clear()
languages


Out[29]:
set()

In [30]:
# add multiple elements 
languages.update(['go', 'spark'])
languages.update({'spark', 'haskell'})
languages


Out[30]:
{'go', 'haskell', 'spark'}

4. Set Operations


In [33]:
languages = {'python', 'r', 'java'}
snakes = set(['cobra', 'viper', 'python'])

In [34]:
# intersection
languages & snakes


Out[34]:
{'python'}

In [35]:
# union
languages | snakes


Out[35]:
{'cobra', 'java', 'python', 'r', 'viper'}

In [36]:
# set difference
languages - snakes


Out[36]:
{'java', 'r'}